import { fetchSubProjectAttendance, fetchSubProjectSummary } from '../../../api/project';

Page({
  data: {
    subProjectId: null,
    subProjectName: '',
    currentDate: '',
    attendanceList: [],
    worktime: 0,
    overtime: 0
  },

  onLoad(options) {
    const { subProjectId, subProjectName } = options;
    this.setData({ subProjectId, subProjectName });
    const currentDate = new Date().toISOString().slice(0, 7);
    this.setData({ currentDate });
    this.fetchData();
  },

  fetchData() {
    const { subProjectId, currentDate } = this.data;
    if (currentDate) {
      this.fetchAttendance(subProjectId, currentDate);
      this.fetchSummary(subProjectId, currentDate);
    }
  },

  fetchAttendance(subProjectId, date) {
    fetchSubProjectAttendance(subProjectId, date).then(response => {
      if (response.code === 1) {
        const sortedData = response.data.sort((a, b) => new Date(a.date) - new Date(b.date));
        const formattedData = sortedData.map(item => ({
          ...item,
          formattedDate: item.date.substring(5) // 只显示月和日
        }));
        this.setData({ attendanceList: formattedData });
      } else {
        console.error('Failed to fetch attendance data');
      }
    }).catch(error => {
      console.error('Error fetching attendance data:', error);
    });
  },

  fetchSummary(subProjectId, date) {
    fetchSubProjectSummary(subProjectId, date).then(response => {
      if (response.code === 1) {
        this.setData({
          worktime: response.data.worktime,
          overtime: response.data.overtime
        });
      } else {
        this.setData({
          worktime: 0,
          overtime: 0
        });
        console.error('Failed to fetch summary data');
      }
    }).catch(error => {
      this.setData({
        worktime: 0,
        overtime: 0
      });
      console.error('Error fetching summary data:', error);
    });
  },

  onDateChange(event) {
    this.setData({ currentDate: event.detail.value }, () => {
      this.fetchData();
    });
  }
});
